{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "335a5de6",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import sys  \n",
    "import json\n",
    "import torch \n",
    "import argparse\n",
    "import shortuuid\n",
    "import numpy as np\n",
    "from PIL import Image \n",
    "from tqdm import tqdm \n",
    "from utils import model_gen, load_jsonl\n",
    "from transformers import AutoModelForCausalLM, AutoTokenizer  \n",
    "  \n",
    "ckpt_path = 'internlm/internlm-xcomposer2-vl-7b'\n",
    "tokenizer = AutoTokenizer.from_pretrained(ckpt_path, trust_remote_code=True)\n",
    "model = AutoModelForCausalLM.from_pretrained(ckpt_path, device_map=\"cuda\", trust_remote_code=True).eval().cuda().half()\n",
    "model.tokenizer = tokenizer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "733859a2",
   "metadata": {
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "meta_instruction = \"\"\"You are an AI assistant whose name is InternLM-XComposer (浦语·灵笔).\n",
    "- InternLM-XComposer (浦语·灵笔) is a multi-modality conversational language model that is developed by Shanghai AI Laboratory (上海人工智能实验室). It is designed to be helpful, honest, and harmless.\n",
    "- InternLM-XComposer (浦语·灵笔) can understand and communicate fluently in the language chosen by the user such as English and 中文.\n",
    "- InternLM-XComposer (浦语·灵笔) is capable of comprehending and articulating responses effectively based on the provided image.\"\"\"\n",
    "\n",
    "samples = load_jsonl('LLaVA_Wild/questions.jsonl')\n",
    "ans_file = open('LLaVA_Wild/LLaVA_wild_InternLM_XComposer_VL.jsonl', \"w\")\n",
    "for q in tqdm(samples):\n",
    "    im_path = 'data/llava-bench-in-the-wild/images/'+q['image']\n",
    "    text = '[UNUSED_TOKEN_146]system\\n{}[UNUSED_TOKEN_145]\\n[UNUSED_TOKEN_146]user\\n{}Answer this question in detail.[UNUSED_TOKEN_145]\\n[UNUSED_TOKEN_146]assistant\\n'.format(meta_instruction, q['text'])\n",
    "    with torch.cuda.amp.autocast(): \n",
    "        out = model_gen(model, text, im_path) \n",
    "    ans_file.write(json.dumps({\"question_id\": q['question_id'],\n",
    "                               \"prompt\": text,\n",
    "                               \"text\": out,\n",
    "                               \"answer_id\": shortuuid.uuid(),\n",
    "                               \"model_id\": 'InternLM_XComposer2_VL',\n",
    "                               \"metadata\": {}}) + \"\\n\")\n",
    "    ans_file.flush()\n",
    "ans_file.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "40b4966a",
   "metadata": {},
   "outputs": [],
   "source": [
    "import openai\n",
    "openai.api_key=''\n",
    "import time\n",
    "\n",
    "NUM_SECONDS_TO_SLEEP = 0.5\n",
    "def get_eval(content: str, max_tokens: int):\n",
    "    while True:\n",
    "        try:\n",
    "            response = openai.ChatCompletion.create(\n",
    "                model='gpt-4-0314',\n",
    "                messages=[{\n",
    "                    'role': 'system',\n",
    "                    'content': 'You are a helpful and precise assistant for checking the quality of the answer.'\n",
    "                }, {\n",
    "                    'role': 'user',\n",
    "                    'content': content,\n",
    "                }],\n",
    "                temperature=0.2,  # TODO: figure out which temperature is best for evaluation\n",
    "                max_tokens=max_tokens,\n",
    "            )\n",
    "            break\n",
    "        except openai.error.RateLimitError:\n",
    "            pass\n",
    "        except Exception as e:\n",
    "            print(e)\n",
    "        time.sleep(NUM_SECONDS_TO_SLEEP)\n",
    "\n",
    "    return response['choices'][0]['message']['content']\n",
    "\n",
    "\n",
    "def parse_score(review):\n",
    "    try:\n",
    "        score_pair = review.split('\\n')[0]\n",
    "        score_pair = score_pair.replace(',', ' ')\n",
    "        sp = score_pair.split(' ')\n",
    "        if len(sp) == 2:\n",
    "            return [float(sp[0]), float(sp[1])]\n",
    "        else:\n",
    "            print('error', review)\n",
    "            return [-1, -1]\n",
    "    except Exception as e:\n",
    "        print(e)\n",
    "        print('error', review)\n",
    "        return [-1, -1]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "698d3ee1",
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "if 1:\n",
    "    f_q = open('LLaVA_Wild/questions.jsonl')\n",
    "    f_ans1 = open('LLaVA_Wild/answers_gpt4.jsonl')\n",
    "    f_ans2 = open('LLaVA_Wild/LLaVA_wild_InternLM_XComposer_VL.jsonl')\n",
    "    rule_dict = {\n",
    "        \"coding\": {\"role\": \"Assistant\", \"prompt\": \"Your task is to evaluate the coding abilities of the above two assistants. They have been asked to implement a program to solve a given problem. Please review their code submissions, paying close attention to their problem-solving approach, code structure, readability, and the inclusion of helpful comments.\\n\\nPlease ensure that the assistants' submissions:\\n\\n1. Correctly implement the given problem statement.\\n2. Contain accurate and efficient code.\\n3. Include clear and concise comments that explain the code's logic and functionality.\\n4. Adhere to proper coding standards and best practices.\\n\\nOnce you have carefully reviewed both submissions, provide detailed feedback on their strengths and weaknesses, along with any suggestions for improvement. You should first output a single line containing two scores on the scale of 1-10 (1: no code/no sense; 10: perfect) for Assistant 1 and 2, respectively. Then give extra comments starting from the next line.\"},\n",
    "        \"math\":  {\"role\": \"Assistant\", \"prompt\": \"We would like to request your feedback on the mathematical proficiency of two AI assistants regarding the given user question.\\nFirstly, please solve the problem independently, without referring to the answers provided by Assistant 1 and Assistant 2.\\nAfterward, please examine the problem-solving process of Assistant 1 and Assistant 2 step-by-step to ensure their correctness, identifying any incorrect steps if present. Your evaluation should take into account not only the answer but also the problem-solving steps.\\nFinally, please output a Python tuple containing two numerical scores for Assistant 1 and Assistant 2, ranging from 1 to 10, respectively. If applicable, explain the reasons for any variations in their scores and determine which assistant performed better.\"},\n",
    "        \"default\":  {\"role\": \"Assistant\", \"prompt\": \"We would like to request your feedback on the performance of two AI assistants in response to the user question displayed above.\\nPlease rate the helpfulness, relevance, accuracy, level of details of their responses. Each assistant receives an overall score on a scale of 1 to 10, where a higher score indicates better overall performance.\\nPlease first output a single line containing only two values indicating the scores for Assistant 1 and 2, respectively. The two scores are separated by a space.\\nIn the subsequent line, please provide a comprehensive explanation of your evaluation, avoiding any potential bias and ensuring that the order in which the responses were presented does not affect your judgment.\"},\n",
    "        \"conv\":  {\"role\": \"Assistant\", \"prompt\": \"We would like to request your feedback on the performance of two AI assistants in response to the user question displayed above. The user asks the question on observing an image. For your reference, the visual content in the image is represented with five descriptive sentences describing the same image and the bounding box coordinates of each object in the scene. These coordinates are in the form of bounding boxes, represented as (x1, y1, x2, y2) with floating numbers ranging from 0 to 1. These values correspond to the top left x, top left y, bottom right x, and bottom right y. \\nPlease rate the helpfulness, relevance, accuracy, level of details of their responses. Each assistant receives an overall score on a scale of 1 to 10, where a higher score indicates better overall performance.\\nPlease first output a single line containing only two values indicating the scores for Assistant 1 and 2, respectively. The two scores are separated by a space.\\nIn the subsequent line, please provide a comprehensive explanation of your evaluation, avoiding any potential bias and ensuring that the order in which the responses were presented does not affect your judgment.\"},\n",
    "        \"detail\":  {\"role\": \"Assistant\", \"prompt\": \"We would like to request your feedback on the performance of two AI assistants in response to the user question displayed above. The user asks the question on observing an image. For your reference, the visual content in the image is represented with five descriptive sentences describing the same image and the bounding box coordinates of each object in the scene. These coordinates are in the form of bounding boxes, represented as (x1, y1, x2, y2) with floating numbers ranging from 0 to 1. These values correspond to the top left x, top left y, bottom right x, and bottom right y. \\nPlease rate the helpfulness, relevance, accuracy, level of details of their responses. Each assistant receives an overall score on a scale of 1 to 10, where a higher score indicates better overall performance.\\nPlease first output a single line containing only two values indicating the scores for Assistant 1 and 2, respectively. The two scores are separated by a space.\\nIn the subsequent line, please provide a comprehensive explanation of your evaluation, avoiding any potential bias and ensuring that the order in which the responses were presented does not affect your judgment.\"},\n",
    "        \"complex\":  {\"role\": \"Assistant\", \"prompt\": \"We would like to request your feedback on the performance of two AI assistants in response to the user question displayed above. The user asks the question on observing an image. For your reference, the visual content in the image is represented with five descriptive sentences describing the same image and the bounding box coordinates of each object in the scene. These coordinates are in the form of bounding boxes, represented as (x1, y1, x2, y2) with floating numbers ranging from 0 to 1. These values correspond to the top left x, top left y, bottom right x, and bottom right y. \\nPlease rate the helpfulness, relevance, accuracy, level of details of their responses. Each assistant receives an overall score on a scale of 1 to 10, where a higher score indicates better overall performance.\\nPlease first output a single line containing only two values indicating the scores for Assistant 1 and 2, respectively. The two scores are separated by a space.\\nIn the subsequent line, please provide a comprehensive explanation of your evaluation, avoiding any potential bias and ensuring that the order in which the responses were presented does not affect your judgment.\"},\n",
    "        \"llava_bench_conv\":  {\"role\": \"Assistant\", \"prompt\": \"We would like to request your feedback on the performance of two AI assistants in response to the user question displayed above. The user asks the question on observing an image. For your reference, the visual content in the image is represented with a few sentences describing the image. \\nPlease rate the helpfulness, relevance, accuracy, level of details of their responses. Each assistant receives an overall score on a scale of 1 to 10, where a higher score indicates better overall performance.\\nPlease first output a single line containing only two values indicating the scores for Assistant 1 and 2, respectively. The two scores are separated by a space.\\nIn the subsequent line, please provide a comprehensive explanation of your evaluation, avoiding any potential bias and ensuring that the order in which the responses were presented does not affect your judgment.\"},\n",
    "        \"llava_bench_detail\":  {\"role\": \"Assistant\", \"prompt\": \"We would like to request your feedback on the performance of two AI assistants in response to the user question displayed above. The user asks the question on observing an image. For your reference, the visual content in the image is represented with a few sentences describing the image. \\nPlease rate the helpfulness, relevance, accuracy, level of details of their responses. Each assistant receives an overall score on a scale of 1 to 10, where a higher score indicates better overall performance.\\nPlease first output a single line containing only two values indicating the scores for Assistant 1 and 2, respectively. The two scores are separated by a space.\\nIn the subsequent line, please provide a comprehensive explanation of your evaluation, avoiding any potential bias and ensuring that the order in which the responses were presented does not affect your judgment.\"},\n",
    "        \"llava_bench_complex\":  {\"role\": \"Assistant\", \"prompt\": \"We would like to request your feedback on the performance of two AI assistants in response to the user question displayed above. The user asks the question on observing an image. For your reference, the visual content in the image is represented with a few sentences describing the image. \\nPlease rate the helpfulness, relevance, accuracy, level of details of their responses. Each assistant receives an overall score on a scale of 1 to 10, where a higher score indicates better overall performance.\\nPlease first output a single line containing only two values indicating the scores for Assistant 1 and 2, respectively. The two scores are separated by a space.\\nIn the subsequent line, please provide a comprehensive explanation of your evaluation, avoiding any potential bias and ensuring that the order in which the responses were presented does not affect your judgment.\"}\n",
    "    }\n",
    "    output_file = 'LLaVA_Wild/LLaVA_wild_Eval_InternLM_XComposer_VL.jsonl'\n",
    "    if os.path.isfile(output_file):\n",
    "        cur_reviews = [json.loads(line) for line in open(output_file)]\n",
    "    else:\n",
    "        cur_reviews = []\n",
    "\n",
    "    review_file = open(f'{output_file}', 'a')\n",
    "\n",
    "    context_list = [json.loads(line) for line in open('/mnt/petrelfs/share_data/chenlin/llava/data/eval/llava-bench-in-the-wild/context.jsonl')]\n",
    "    image_to_context = {context['image']: context for context in context_list}\n",
    "\n",
    "    handles = []\n",
    "    idx = 0\n",
    "    for ques_js, ans1_js, ans2_js in zip(f_q, f_ans1, f_ans2):\n",
    "        ques = json.loads(ques_js)\n",
    "        ans1 = json.loads(ans1_js)\n",
    "        ans2 = json.loads(ans2_js)\n",
    "\n",
    "        inst = image_to_context[ques['image']]\n",
    "\n",
    "        if isinstance(inst['caption'], list):\n",
    "            cap_str = '\\n'.join(inst['caption'])\n",
    "        else:\n",
    "            cap_str = inst['caption']\n",
    "\n",
    "        category = 'llava_bench_' + json.loads(ques_js)['category']\n",
    "        if category in rule_dict:\n",
    "            rule = rule_dict[category]\n",
    "        else:\n",
    "            assert False, f\"Visual QA category not found in rule file: {category}.\"\n",
    "        prompt = rule['prompt']\n",
    "        role = rule['role']\n",
    "        content = (f'[Context]\\n{cap_str}\\n\\n'\n",
    "                   f'[Question]\\n{ques[\"text\"]}\\n\\n'\n",
    "                   f'[{role} 1]\\n{ans1[\"text\"]}\\n\\n[End of {role} 1]\\n\\n'\n",
    "                   f'[{role} 2]\\n{ans2[\"text\"]}\\n\\n[End of {role} 2]\\n\\n'\n",
    "                   f'[System]\\n{prompt}\\n\\n')\n",
    "        cur_js = {\n",
    "            'id': idx+1,\n",
    "            'question_id': ques['question_id'],\n",
    "            'answer1_id': ans1.get('answer_id', ans1['question_id']),\n",
    "            'answer2_id': ans2.get('answer_id', ans2['answer_id']),\n",
    "            'category': category\n",
    "        }\n",
    "        if idx >= len(cur_reviews):\n",
    "            review = get_eval(content, 1024)\n",
    "            scores = parse_score(review)\n",
    "            cur_js['content'] = review\n",
    "            cur_js['tuple'] = scores\n",
    "            review_file.write(json.dumps(cur_js) + '\\n')\n",
    "            review_file.flush()\n",
    "        else:\n",
    "            print(f'Skipping {idx} as we already have it.')\n",
    "        idx += 1\n",
    "    review_file.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9a5231a7",
   "metadata": {},
   "outputs": [],
   "source": [
    "from collections import defaultdict\n",
    "scores = defaultdict(list) \n",
    "with open('LLaVA_Wild/LLaVA_wild_Eval_InternLM_XComposer_VL.jsonl', 'r') as f:\n",
    "    for review_str in f:\n",
    "        review = json.loads(review_str)\n",
    "        if 'category' in review:\n",
    "            scores[review['category']].append(review['tuple'])\n",
    "            scores['all'].append(review['tuple'])\n",
    "        else:\n",
    "            if 'tuple' in review:\n",
    "                scores['all'].append(review['tuple'])\n",
    "            else:\n",
    "                scores['all'].append(review['score'])\n",
    "    for k, v in sorted(scores.items()):\n",
    "        stats = np.asarray(v).mean(0).tolist()\n",
    "        stats = [round(x, 3) for x in stats]\n",
    "        # print(k, stats, round(stats[1]/stats[0]*100, 1))\n",
    "        print(k, round(stats[1]/stats[0]*100, 1), round(stats[0] * 10, 1), round(stats[1] * 10, 1))\n",
    "print('=================================')\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e3d35bb8",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
